from rest_framework import serializers
from .models import (
    DatabaseConnection, DatabaseBackup, DatabaseMonitoring, 
    QueryHistory, DatabaseAlert
)


class DatabaseConnectionSerializer(serializers.ModelSerializer):
    """数据库连接序列化器"""
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    
    class Meta:
        model = DatabaseConnection
        fields = [
            'id', 'name', 'host', 'port', 'database', 'username', 
            'engine', 'is_active', 'is_default', 'created_by', 
            'created_by_name', 'created_at', 'updated_at'
        ]
        extra_kwargs = {
            'password': {'write_only': True},
            'created_by': {'read_only': True}
        }

    def create(self, validated_data):
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class DatabaseConnectionCreateSerializer(serializers.ModelSerializer):
    """数据库连接创建序列化器（包含密码）"""
    
    class Meta:
        model = DatabaseConnection
        fields = [
            'name', 'host', 'port', 'database', 'username', 
            'password', 'engine', 'is_active', 'is_default'
        ]

    def create(self, validated_data):
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class DatabaseBackupSerializer(serializers.ModelSerializer):
    """数据库备份序列化器"""
    connection_name = serializers.CharField(source='connection.name', read_only=True)
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    file_size_mb = serializers.SerializerMethodField()
    
    class Meta:
        model = DatabaseBackup
        fields = [
            'id', 'connection', 'connection_name', 'name', 'file_path', 
            'file_size', 'file_size_mb', 'backup_type', 'status', 
            'error_message', 'created_by', 'created_by_name', 
            'created_at', 'completed_at'
        ]
        extra_kwargs = {
            'created_by': {'read_only': True}
        }

    def get_file_size_mb(self, obj):
        """获取文件大小（MB）"""
        if obj.file_size:
            return round(obj.file_size / (1024 * 1024), 2)
        return 0

    def create(self, validated_data):
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class DatabaseMonitoringSerializer(serializers.ModelSerializer):
    """数据库监控序列化器"""
    connection_name = serializers.CharField(source='connection.name', read_only=True)
    database_size_mb = serializers.SerializerMethodField()
    
    class Meta:
        model = DatabaseMonitoring
        fields = [
            'id', 'connection', 'connection_name', 'cpu_usage', 'memory_usage', 
            'disk_usage', 'connection_count', 'active_queries', 'slow_queries', 
            'table_count', 'database_size', 'database_size_mb', 'response_time', 
            'created_at'
        ]

    def get_database_size_mb(self, obj):
        """获取数据库大小（MB）"""
        if obj.database_size:
            return round(obj.database_size / (1024 * 1024), 2)
        return 0


class QueryHistorySerializer(serializers.ModelSerializer):
    """SQL查询历史序列化器"""
    connection_name = serializers.CharField(source='connection.name', read_only=True)
    executed_by_name = serializers.CharField(source='executed_by.username', read_only=True)
    
    class Meta:
        model = QueryHistory
        fields = [
            'id', 'connection', 'connection_name', 'query', 'query_type', 
            'execution_time', 'rows_affected', 'status', 'error_message', 
            'executed_by', 'executed_by_name', 'executed_at'
        ]
        extra_kwargs = {
            'executed_by': {'read_only': True}
        }

    def create(self, validated_data):
        validated_data['executed_by'] = self.context['request'].user
        return super().create(validated_data)


class DatabaseAlertSerializer(serializers.ModelSerializer):
    """数据库告警序列化器"""
    connection_name = serializers.CharField(source='connection.name', read_only=True)
    resolved_by_name = serializers.CharField(source='resolved_by.username', read_only=True)
    
    class Meta:
        model = DatabaseAlert
        fields = [
            'id', 'connection', 'connection_name', 'alert_type', 'severity', 
            'message', 'threshold_value', 'current_value', 'is_resolved', 
            'resolved_at', 'resolved_by', 'resolved_by_name', 'created_at'
        ]
        extra_kwargs = {
            'resolved_by': {'read_only': True}
        }


class SQLQuerySerializer(serializers.Serializer):
    """SQL查询序列化器"""
    connection_id = serializers.IntegerField()
    query = serializers.CharField()
    
    def validate_query(self, value):
        """验证SQL查询"""
        # 基本的SQL注入防护
        dangerous_keywords = [
            'DROP DATABASE', 'DROP TABLE', 'TRUNCATE', 'DELETE FROM',
            'UPDATE', 'INSERT INTO', 'CREATE', 'ALTER', 'GRANT', 'REVOKE'
        ]
        
        query_upper = value.upper()
        for keyword in dangerous_keywords:
            if keyword in query_upper:
                raise serializers.ValidationError(f"不允许执行包含 '{keyword}' 的查询")
        
        return value


class DatabaseStatsSerializer(serializers.Serializer):
    """数据库统计序列化器"""
    total_connections = serializers.IntegerField()
    active_connections = serializers.IntegerField()
    total_backups = serializers.IntegerField()
    recent_backups = serializers.IntegerField()
    total_queries = serializers.IntegerField()
    recent_queries = serializers.IntegerField()
    active_alerts = serializers.IntegerField()
    resolved_alerts = serializers.IntegerField()
